package kyssion.leetcode.num201_250;

import kyssion.leetcode.util.TreeNode;

public class code230_二叉搜索树中第K小的元素 {

    public static void main(String[] args) {
        System.out.println(new code230_二叉搜索树中第K小的元素().kthSmallest(
                TreeNode.create(new int[]{
                        3,1,4,-1,2
                }),1
        ));
    }

    int index;
    int now;
    int item;

    public int kthSmallest(TreeNode root, int k) {
        this.index = k;
        ans(root);
        return item;
    }

    private void ans(TreeNode root) {
        if (root == null || now >= index) {
            return;
        }
        ans(root.left);
        now++;
        if (now == index) {
            item = root.val;
            return;
        }
        ans(root.right);
    }

}
